package wiki;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.Root;


import java.io.*;



/**
 * 
 * @author mona.chandrapal
 */
public class filetodb extends HttpServlet {

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		//PrintWriter out = response.getWriter();
		
		
		Root root = new Root();
		ResultSet rs = null;
		PreparedStatement pst = null;

			
		// Create path components to save the file
	     String path = request.getParameter("destination");
	     Part filePart = request.getPart("file");
	     String fileName = getFileName(filePart);

	    OutputStream out = null;
	    InputStream filecontent = null;
	    PrintWriter writer = response.getWriter();

	    try {
	        out = new FileOutputStream(new File(path + File.separator
	                + fileName));
	        filecontent = filePart.getInputStream();

	        int read = 0;
	        final byte[] bytes = new byte[1024];

	        while ((read = filecontent.read(bytes)) != -1) {
	            out.write(bytes, 0, read);
	        }
	        System.out.println("New file " + fileName + " created at " + path);
	        System.out.println("File being uploaded to server");
	    } catch (FileNotFoundException fne) {
	    	System.out.println("You either did not specify a file to upload or are "
	                + "trying to upload a file to a protected or nonexistent "
	                + "location.");
	        System.out.println("<br/> ERROR: " + fne.getMessage());

	        System.out.println("Problems during file upload. Error: {0}");
	    } finally {
	        if (out != null) {
	            out.close();
	        }
	        if (filecontent != null) {
	            filecontent.close();
	        }
	        if (writer != null) {
	            writer.close();
	        }
	    }
		      
		
		
		
		
        
		
		try {

			String sql1;
			File image = new File("C:\\test.png");
			System.out.println("File read !");

			// declare FileInputStream object to store binary stream of given
			// image.
			FileInputStream fis;
			fis = new FileInputStream(image);
			System.out.println("File converted !");

			root.initConnection();

			sql1 = "insert into attachedfile(filename, file) values(?,?)";
			pst = root.con.prepareStatement(sql1);
			pst.setString(1, "Test");

			pst.setBinaryStream(2, (InputStream) fis, (int) (image.length()));
			/*
			 * executeUpdate() method execute specified sql query. Here this
			 * query insert data and image from specified address.
			 */
			int s = pst.executeUpdate();
			if (s > 0) {
				System.out.println("Uploaded successfully !");
				System.out.println(image);
			} else {
				System.out.println("unsucessfull to upload image.");
			}


		} catch (Exception e) {
			System.out.println("Exception uploading file: " + e.toString());
		} finally {
			try {
				pst.close();
				rs.close();
				root.closeConnection();
			} catch (Exception e) {

			}

		}

		System.out.println("File To DB");
		
		
	}
	

	private String getFileName(final Part part) {
	    final String partHeader = part.getHeader("content-disposition");
	    System.out.println("Part Header = {0}");
	    for (String content : part.getHeader("content-disposition").split(";")) {
	        if (content.trim().startsWith("filename")) {
	            return content.substring(
	                    content.indexOf('=') + 1).trim().replace("\"", "");
	        }
	    }
	    return null;
	}
	
	// <editor-fold defaultstate="collapsed"
	// desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

	/**
	 * Handles the HTTP <code>GET</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 * 
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
